﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Xml;

using System.ServiceModel;
using System.ServiceModel.Description;

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Client.Configuration;
using Microsoft.Xrm.Portal;
using Microsoft.Xrm;

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Crm.Services.Utility;

namespace CRM2ORCH
{
    
    public class Update
    {
        public OrganizationService service;
        public string message = string.Empty;

        public string updateEntityByGuid(String entity, String objectGuid, String attributeName, String updateValueNameOrGuid)
        {
            try
            {
                Connection conn = new Connection();
                service = conn.setConnection();
                Guid guid = new Guid(objectGuid);
                //get object using guid
                Entity oggettoCrm = (Entity)service.Retrieve(entity, guid, new ColumnSet(allColumns: true));
                //search for attribute type

                //update attribute
                //is an entityreference?
                String entityType = oggettoCrm[attributeName].GetType().ToString();
                String type = ((EntityReference)oggettoCrm[attributeName]).LogicalName;
                if (entityType.Equals("Microsoft.Xrm.Sdk.EntityReference"))
                {
                    Guid updateValueGuid = new Guid(updateValueNameOrGuid);
                    Entity updateValue = (Entity)service.Retrieve(type, updateValueGuid, new ColumnSet(allColumns: true));
                    oggettoCrm[attributeName] = updateValue;
                }
                else
                {
                    oggettoCrm[attributeName] = updateValueNameOrGuid;
                }

                //update object on CRM
                service.Update(oggettoCrm);
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return message;
        }
    }
}